package com.zr.bookcorner.activity;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zh.baselibrary.base.BaseActivity;
import com.zh.baselibrary.base.BasePresenter;
import com.zh.baselibrary.base.BaseRecyclerAdapter;
import com.zh.baselibrary.constant.BaseConstant;
import com.zh.baselibrary.constant.ExtraName;
import com.zh.baselibrary.model.BookModel;
import com.zh.baselibrary.netutils.BaseResp;
import com.zh.baselibrary.rxjava.RxSubscribe;
import com.zh.baselibrary.utils.ComparatorUtils;
import com.zh.baselibrary.utils.IntentUtils;
import com.zh.baselibrary.utils.KeyBoardUtils;
import com.zh.baselibrary.utils.PhoneUtil;
import com.zh.baselibrary.utils.ShareManager;
import com.zh.baselibrary.utils.TTSUtils;
import com.zh.baselibrary.views.SearchView;
import com.zh.baselibrary.views.ToastView;
import com.zh.model.manager.BookInfo;
import com.zh.model.manager.SearchBook;
import com.zr.andealib.util.HardEvent;
import com.zr.andealib.util.constant.AndeaConstant;
import com.zr.bookcorner.R;
import com.zr.bookcorner.adapter.BookQueryAdapter;
import com.zr.bookcorner.dialog.ManagerVerificationDialog;
import com.zr.bookcorner.presenter.QueryPresenter;
import com.zr.bookcorner.presenter.view.QueryView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnEditorAction;
import butterknife.OnTextChanged;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class QueryBookActivity extends BaseActivity<QueryPresenter> implements QueryView, BaseRecyclerAdapter.OnItemViewClickListener {
    @BindView(R.id.rv_book)
    RecyclerView mRvBook;
    @BindView(R.id.sv_text)
    SearchView mSvText;
    BookQueryAdapter mAdapter;
    private ManagerVerificationDialog mVerificationDialog;
    BookModel model;
    boolean isLoading = false;
    boolean hasMore = true;
    boolean isMore = false;
    int pageNum = 1;
    private int boxNum;

    @Override
    protected int getLayoutId() {
        return R.layout.query_book_activity;
    }

    @Override
    protected void init() {
        mAdapter = new BookQueryAdapter(new ArrayList<>());
        mRvBook.setLayoutManager(new LinearLayoutManager(this));
        mRvBook.setAdapter(mAdapter);
        mAdapter.setOnItemViewClickListener(this);
        mRvBook.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int lastVisibleItem;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == mAdapter.getItemCount()) {
                    if (!isLoading && hasMore) {
                        isLoading = true;
                        isMore = true;
                        mAdapter.changeMoreStatus(BookQueryAdapter.LOADING_MORE);
                        mPresenter.queryBook(mSvText.getText().toString(), pageNum);
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });

        model = new BookModel(this);
        mPresenter.queryBook("", pageNum);
        mPresenter.count();

    }

    //键盘反馈
    @OnEditorAction(R.id.sv_text)
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            KeyBoardUtils.closeKeybord(mSvText, this);
        }
        return false;
    }

    @OnTextChanged({R.id.sv_text})
    public void onTextChanged(CharSequence text, int start, int before, int count) {
        pageNum = 1;
        hasMore = true;
        isMore = false;
        mPresenter.queryBook(mSvText.getText().toString(), pageNum);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(HardEvent hardEvent) {
        int flag = hardEvent.getFlag();
        if (flag == AndeaConstant.CALL_VERIFICATION_SUCCSES) {  //磁卡登录
            String code = (String) hardEvent.getData();
            mPresenter.checkCard(code);
        } else if (flag == AndeaConstant.CALL_LOCK_STATUS_SUCCSES) {
            dismissDialog();
            Bundle bundle = new Bundle();
            bundle.putInt(ExtraName.KEY_DATA, boxNum);
            IntentUtils.instance().startActivity(this, BorrowReturnDetailActivity.class, bundle);
            TTSUtils.getInstance().speak(getString(R.string.open_success));
        } else if (flag == AndeaConstant.CALL_INIT_VERIFICATION_ERROR||flag == AndeaConstant.CALL_LOCK_STATUS_ERROR) {
            String msg = (String) hardEvent.getData();
            ToastView.showLong(msg);
            if(!msg.equals("柜门处于开启状态")) {
                TTSUtils.getInstance().speak(getString(R.string.open_error));
            }


        }
    }

    @Override
    protected QueryPresenter createPresenter() {
        return new QueryPresenter();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        KeyBoardUtils.closeKeybord(mSvText, this);
        return super.onTouchEvent(event);
    }

    @Override
    public void showDialog() {
        mVerificationDialog = new ManagerVerificationDialog(this, R.style.DialogTheme, null);
        mVerificationDialog.setShowQRCode(false);
        mVerificationDialog.show();
    }

    private void dismissDialog() {
        if (mVerificationDialog != null && mVerificationDialog.isShowing())
            mVerificationDialog.cancel();
    }

    @Override
    public void defyError() {
        dismissDialog();
        TTSUtils.getInstance().speak(getString(R.string.defy_error));
    }

    @Override
    public void onHint(String hint) {
        super.onHint(hint);
        isLoading = false;
    }

    @Override
    public void getDataSuccess(SearchBook book) {
        isLoading = false;
        if (isMore)
            mAdapter.addData(book.getList());
        else
            mAdapter.clearAdd(book.getList());

        if (book.isLastPage()) {
            mAdapter.changeMoreStatus(BookQueryAdapter.NO_MORE);
            hasMore = false;
        } else {
            mAdapter.changeMoreStatus(BookQueryAdapter.TO_MORE);
            pageNum++;
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.initLock();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPresenter.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onItemViewClick(View v, int position) {
        boxNum = position;
        mPresenter.checkDoorStatus(position);
    }
}
